package com.gewu.pm.ui.fragment.home;

import android.app.DatePickerDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.app.AppFragment;
import com.gewu.pm.bean.TestBean;
import com.gewu.pm.ui.adapter.home.MonthlyTableAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;


/**
 * 打卡报表-月度汇总
 */
public final class MonthlySummaryFragment extends AppFragment<AppActivity> {

    private ImageView mDatePrev;
    private TextView mSelectedDate;
    private ImageView mDateNext;
    private RecyclerView mRecyclerView;
    private MonthlyTableAdapter mAdapter;
    private Calendar mCurrentDate;
    private SimpleDateFormat mDateFormat;
    private SimpleDateFormat mYearDateFormat;

    public static MonthlySummaryFragment newInstance() {
        return new MonthlySummaryFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_monthly_summary;
    }

    @Override
    protected void initView() {
        mDatePrev = findViewById(R.id.iv_date_prev);
        mSelectedDate = findViewById(R.id.tv_selected_date);
        mDateNext = findViewById(R.id.iv_date_next);
        mRecyclerView = findViewById(R.id.rv_employee_list);

        // 初始化日期格式化器
        mDateFormat = new SimpleDateFormat("yyyy年MM月", Locale.getDefault());
        mYearDateFormat = new SimpleDateFormat("yyyy年MM月", Locale.getDefault());

        // 初始化当前日期
        mCurrentDate = Calendar.getInstance();
        
        // 设置点击事件
        setOnClickListener(mDatePrev, mSelectedDate, mDateNext);
        
        // 初始化表格
        setupTable();
    }

    @Override
    protected void initData() {
        // 更新日期显示
        updateDateDisplay();
        
        // 加载表格数据
        loadTableData();
    }
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_date_prev) {
            // 月份减1
            mCurrentDate.add(Calendar.MONTH, -1);
            updateDateDisplay();
            loadTableData();

        } else if (id == R.id.tv_selected_date) {
            // 显示日期选择器
            showDatePicker();

        } else if (id == R.id.iv_date_next) {
            // 月份加1
            mCurrentDate.add(Calendar.MONTH, 1);
            updateDateDisplay();
            loadTableData();

        }
    }
    /**
     * 更新日期显示
     */
    private void updateDateDisplay() {
        Calendar today = Calendar.getInstance();
        boolean isCurrentYear = mCurrentDate.get(Calendar.YEAR) == today.get(Calendar.YEAR);

        String dateText;
        if (isCurrentYear) {
            // 今年显示：X年X月
            dateText = mDateFormat.format(mCurrentDate.getTime());
        } else {
            // 非今年显示：X年X月
            dateText = mYearDateFormat.format(mCurrentDate.getTime());
        }

        mSelectedDate.setText(dateText);
    }

    /**
     * 显示日期选择器
     */
    private void showDatePicker() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                getContext(),
                (view, year, month, dayOfMonth) -> {
                    mCurrentDate.set(year, month, dayOfMonth);
                    updateDateDisplay();

                },
                mCurrentDate.get(Calendar.YEAR),
                mCurrentDate.get(Calendar.MONTH),
                mCurrentDate.get(Calendar.DAY_OF_MONTH)
        );
        datePickerDialog.show();
    }

    /**
     * 初始化表格
     */
    private void setupTable() {
        // 初始化适配器
        mAdapter = new MonthlyTableAdapter(getContext());
        
        // 设置RecyclerView
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);
        
        // 设置表头数据
        setupTableHeader();
    }

    /**
     * 设置表头数据
     */
    private void setupTableHeader() {
        // 获取表头布局中的控件并设置标题
        View headerView = findViewById(R.id.layout_table_header);
        if (headerView != null) {
            TextView tvName = headerView.findViewById(R.id.tv_name);
            TextView tvDepartment = headerView.findViewById(R.id.tv_department);
            TextView tvAttendanceDays = headerView.findViewById(R.id.tv_attendance_days);
            TextView tvNormalDays = headerView.findViewById(R.id.tv_normal_days);
            TextView tvStartDate = headerView.findViewById(R.id.tv_start_date);
            TextView tvEndDate = headerView.findViewById(R.id.tv_end_date);
            TextView tvUnsignedDays = headerView.findViewById(R.id.tv_unsigned_days);
            TextView tvUnsignedOutDays = headerView.findViewById(R.id.tv_unsigned_out_days);
            TextView tvEarlyLeaveDays = headerView.findViewById(R.id.tv_early_leave_days);
            TextView tvLateDays = headerView.findViewById(R.id.tv_late_days);
            TextView tvAbsentDays = headerView.findViewById(R.id.tv_absent_days);
            TextView tvNoPunchDays = headerView.findViewById(R.id.tv_no_punch_days);

            // 设置表头标题
            if (tvName != null) tvName.setText("姓名");
            if (tvDepartment != null) tvDepartment.setText("部门");
            if (tvAttendanceDays != null) tvAttendanceDays.setText("出勤天数");
            if (tvNormalDays != null) tvNormalDays.setText("正常出勤天数");
            if (tvStartDate != null) tvStartDate.setText("考勤开始日期");
            if (tvEndDate != null) tvEndDate.setText("考勤结束日期");
            if (tvUnsignedDays != null) tvUnsignedDays.setText("未签到天数");
            if (tvUnsignedOutDays != null) tvUnsignedOutDays.setText("未签退天数");
            if (tvEarlyLeaveDays != null) tvEarlyLeaveDays.setText("早退（天）");
            if (tvLateDays != null) tvLateDays.setText("迟到（天）");
            if (tvAbsentDays != null) tvAbsentDays.setText("旷工（天）");
            if (tvNoPunchDays != null) tvNoPunchDays.setText("未打卡（天）");
        }
    }

    /**
     * 加载表格数据
     * 使用 TestBean 存储员工考勤数据
     */
    private void loadTableData() {
        List<TestBean> dataList = new ArrayList<>();
        
        // 创建测试数据（使用 TestBean）
        String[] names = {"张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十", "郑十一", "陈十二"};
        
        for (int i = 0; i < names.length; i++) {
            // TestBean 字段说明：
            // - id: 员工ID
            // - name: 员工姓名  
            // - type: 考勤数据（实际项目中可以存储JSON格式的详细数据）
            TestBean employee = new TestBean(
                "EMP" + String.format("%03d", i + 1),  // id: 员工ID
                names[i],                               // name: 员工姓名
                "attendance_data"                       // type: 考勤数据标识
            );
            dataList.add(employee);
        }
        
        // 设置数据到适配器
        mAdapter.setData(dataList);
    }

}
